import { expect } from '@jest/globals';
import { initExecuteCommand, runHvigorAsync } from '@ohos/hvigor-ohos-plugin/test/e2e-test/common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '@ohos/hvigor-ohos-plugin/test/e2e-test/plugins/project-builder/models/constants';
import { TestCaseBuilder } from '@ohos/hvigor-ohos-plugin/test/e2e-test/plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '@ohos/hvigor-ohos-plugin/test/e2e-test/plugins/task-builder/test-case';
import { TestTaskOption } from '@ohos/hvigor-ohos-plugin/test/e2e-test/plugins/task-builder/test-task-option';
import fsExtra from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1,
    [ModuleTemplateType.ListAbility]: 1
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

async function addMiniToJson5(modulePath: string) {
  const buffer = await fsExtra.readFile(path.resolve(modulePath, 'build-profile.json5'));
  const parse = JSON5.parse(buffer.toString());
  parse.targets.push({
    'name': 'mini'
  });
  await fsExtra.writeFile(path.resolve(modulePath, 'build-profile.json5'), JSON5.stringify(parse, null, 2));
}

async function isOutputCorrect(modulePath: string) {
  // 判断结果是否只含有有outputs目录下 有mini 和 default 的hap包
  const existsMiniSignHap =
    (await fsExtra.readdir(path.resolve(modulePath, 'build/default/outputs/mini')))
      .some(item => item.includes('-unsigned.hap'));

  const existsDefaultSignHap =
    (await fsExtra.readdir(path.resolve(modulePath, 'build/default/outputs/default')))
      .some(item => item.includes('-unsigned.hap'));


  return existsMiniSignHap && existsDefaultSignHap;
}

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'module',
    tasks: 'assembleHap',
  });
  const entryPath = project.getModule('entry').moduleRootPath();
  const applicationPath = project.getModule('application').moduleRootPath();
  const listApplicationPath = project.getModule('listApplication').moduleRootPath();
  await addMiniToJson5(entryPath);
  await addMiniToJson5(applicationPath);
  await addMiniToJson5(listApplicationPath);

  const result = await runHvigorAsync(projectRootPath, command);
  record.addStep('执行./hvigorw assembleHap -p product=default2 -p module="entry@mini,application@mini', result);
  expect(result.stdout).toContain('Finished :application:mini@PackageHap');
  expect(result.stdout).toContain('Finished :application:default@PackageHap');
  expect(result.stdout).toContain('Finished :entry:mini@PackageHap');
  expect(result.stdout).toContain('Finished :entry:default@PackageHap');
  expect(result.stdout).toContain('Finished :listApplication:mini@PackageHap');
  expect(result.stdout).toContain('Finished :listApplication:default@PackageHap');
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  expect(await isOutputCorrect(entryPath)).toBe(true);
  expect(await isOutputCorrect(applicationPath)).toBe(true);
  expect(await isOutputCorrect(listApplicationPath)).toBe(true);
};

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_moduleTarget_1_001')
  .description('命令行直接执行多个module多个target的hap包_短命令')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
